//
//  OEOrderViewController.m
//  OneEightyNine
//
//  Created by Mac on 2019/3/8.
//  Copyright © 2019 stoneobs. All rights reserved.
//

#import "OEOrderSearchViewController.h"
#import "STSegementAutoView.h"

#import "OEOrderHeaderView.h"
#import "OEOrderTableViewCell.h"
#import "OEOrderFooterView.h"

#import "OEOrderDetailViewController.h"
#import "OEOrderSearchViewController.h"
@interface OEOrderSearchViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) STSegementAutoView                     *autoView;/**<  */
@property(nonatomic, strong) NSMutableArray<OEOrderModel*>                     *dataSouce;/**< <##> */
@property(nonatomic, strong) UITextField                     *searchTextFied;/**< 搜索 */
@end

@implementation OEOrderSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self configSubView];

    // Do any additional setup after loading the view.
}
#pragma mark --subView
- (void)configSubView{
    
    self.searchTextFied = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth * 0.7, 34)];
    self.searchTextFied.placeholder = @"Search for Order";
    self.searchTextFied.returnKeyType = UIReturnKeySearch;
    self.searchTextFied.backgroundColor = OE_GrayColor;
    self.searchTextFied.layer.cornerRadius = self.searchTextFied.height / 2;
    self.searchTextFied.leftViewMode = UITextFieldViewModeAlways;
    STButton * searchButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 34, 34)
                                                        title:@""
                                                   titleColor:SecendTextColor
                                                    titleFont:0
                                                 cornerRadius:0
                                              backgroundColor:nil
                                              backgroundImage:nil
                                                        image:[UIImage imageNamed:@"24×26搜索"]];
    
    self.searchTextFied.leftView = searchButton;
    self.searchTextFied.delegate = self;
    searchButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    self.navigationItem.titleView = self.searchTextFied;
    
    
    __weak typeof(self) weakSelf =  self;
    self.autoView = [[STSegementAutoView alloc] initWithFrame:CGRectMake(0, TMUtils.navgationBarBootom, UIScreenWidth , 50) andTitle:@[@"ALL",@"ORDER IN PLACE",@"IN USE",@"RETURNED",@"COMPLETE",@"CACNLE"] handle:^(STSegementAutoView *sender, UIButton *currentSelctedButton) {
        [weakSelf.tableView.mj_header beginRefreshing];
        
    }];
    [self.view addSubview:self.autoView];
    self.autoView.lineSelectedColor = OE_LIMITE_COLOR;
    self.autoView.butTitleColor = FirstTextColor;
    self.autoView.butTitleSelectedColor = OE_LIMITE_COLOR;
    self.autoView.lineColor = UIColor.clearColor;
    self.autoView.autoMoveWithClic = YES;
    self.autoView.butonWith = 120;
    
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.frame = CGRectMake(0, self.autoView.bottom, UIScreenWidth, TMUtils.tabBarTop - self.autoView.bottom + 49);
    
    
    self.tableView.st_noreslutView = [[STNoresultView alloc] initWithFrame:CGRectMake(0, self.tableView.tableHeaderView.height + 30, UIScreenWidth, 400) title:@"NO More Data" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf sendNetRequest];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    [self.tableView registerClass:OEOrderTableViewCell.class forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:OEOrderHeaderView.class forHeaderFooterViewReuseIdentifier:@"header"];
    [self.tableView registerClass:OEOrderFooterView.class forHeaderFooterViewReuseIdentifier:@"footer"];
}
#pragma mark --UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [self.tableView.mj_header beginRefreshing];
        
    }
    return YES;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce[section].goods_list.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return OEOrderTableViewCell.cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return OEOrderHeaderView.cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return OEOrderFooterView.cellHeight;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    OEOrderHeaderView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    OEOrderModel * model = self.dataSouce[section];
    header.model = model;
    [header setOnSelctedHeaderHandle:^{
        [TMUtils gotoShopHeaderWithModel:model.supplier_info];
    }];
    return header;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    OEOrderFooterView * footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer"];
    OEOrderModel * model = self.dataSouce[section];
    footer.model = model;
    __weak typeof(self) weakSelf =  self;
    [footer setOnSelctedHandle:^(NSString * _Nonnull title) {
        [weakSelf dealBootomActionWithTitle:title order_id:model.order_id orderModel:model];
    }];
    return footer;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    OEOrderTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    OEOrderModel * model = self.dataSouce[indexPath.section];
    OEGoodModel * goodModel = model.goods_list[indexPath.row];
    cell.model = goodModel;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)dealBootomActionWithTitle:(NSString*)title order_id:(NSString*)order_id orderModel:(OEOrderModel*)orderModel{
    if ([title isEqualToString:@"CANCLE"]) {
        
        [self st_showAlertTitle:@"Are you sure you want to cancle the order？" message:@"" leftTitle:@"NO" rightTitle:@"CANCLE" block:^(NSString *name) {
            if ([name isEqualToString:@"CANCLE"]) {
                [OEOrderDataController sendCancleOrderRequestWithOrder_id:order_id handle:^(BOOL success, NSString * _Nonnull errorString, NSDictionary * _Nonnull resp) {
                    if (success) {
                        [self.tableView.mj_header beginRefreshing];
                    }
                }];
            }
        }];
    }
    if ([title isEqualToString:@"RETURN"]) {
        [self st_showAlertTitle:@"Are you sure you want to return it? After the merchant confirms, you will return successfully" message:@"" leftTitle:@"CANCLE" rightTitle:@"RETURN" block:^(NSString *name) {
            if ([name isEqualToString:@"RETURN"]) {
                [OEOrderDataController sendReturnOrderRequestWithOrder_id:order_id handle:^(BOOL success, NSString * _Nonnull errorString, NSDictionary * _Nonnull resp) {
                    if (success) {
                        [self.tableView.mj_header beginRefreshing];
                    }
                }];
            }
        }];
        
    }
    if ([title isEqualToString:@"DELETE"]) {
        [self st_showAlertTitle:@"Are you sure you want to delete the order？" message:@"" leftTitle:@"CANCLE" rightTitle:@"DELETE" block:^(NSString *name) {
            if ([name isEqualToString:@"DELETE"]) {
                [OEOrderDataController sendDeleteOrderRequestWithOrder_id:order_id handle:^(BOOL success, NSString * _Nonnull errorString, NSDictionary * _Nonnull resp) {
                    if (success) {
                        [self.tableView.mj_header beginRefreshing];
                    }
                }];
            }
        }];
    }
    
    if ([title isEqualToString:@"BUY AGAIN"]) {
        //去店铺
        OEShopEasyModel * model =  OEShopEasyModel.new;
        model.supplier_id = orderModel.supplier_id;
        [TMUtils gotoShopHeaderWithModel:model];
    }
    if ([title isEqualToString:@"DETAIL"]) {
        
        //去详情
        OEOrderDetailViewController * vc = OEOrderDetailViewController.new;
        vc.order_id = order_id;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark --NetWork Method
- (void)sendNetRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * paramDic = [NSMutableDictionary new];
    NSString * token = STUserManger.defult.loginedUser.token;
    if (token.length) {
        [paramDic setObject:token forKey:@"user_token"];
    }
    if (self.searchTextFied.text.length) {
        [paramDic setObject:self.searchTextFied.text forKey:@"keyword"];
    }
    [paramDic setObject:@(self.autoView.cureentIndex) forKey:@"status"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php?m=Front&c=User&a=orderList"];
    DDLogInfo(@"url:%@",url);
    DDLogInfo(@"param:%@",paramDic);
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:paramDic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 //                                                 [STNetWrokManger shownNormalRespMsgWithResponse:responseObject];
                                                 NSDictionary * modelDic = [responseObject valueForKey:@"content"];
                                                 NSArray * array  = modelDic[@"list"];
                                                 self.dataSouce = [OEOrderModel mj_objectArrayWithKeyValuesArray:array];
                                                 [self.tableView reloadData];
                                                 [self.tableView.mj_header endRefreshing];
                                                 DDLogInfo(@"%@请求成功:resp\n%@",url,responseObject);
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error,NSError *originError) {
                                                 [SVProgressHUD dismiss];
                                                 self.dataSouce = [OEOrderModel mj_objectArrayWithKeyValuesArray:@[]];
                                                 [self.tableView reloadData];
                                                 [self.tableView.mj_header endRefreshing];
                                                 DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                                                            url,paramDic,error.desc,error.code);
                                             }];
}
@end
